<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle()" width="600px" @ok="handleOk" :showFooter="showFooter">
    <a-tabs v-model:activeKey="activeKey" @change="handleTabChange" size="small">
      <a-tab-pane tab="用户信息" key="form1">
        <UserForm ref="form1"></UserForm>
      </a-tab-pane>
      <a-tab-pane tab="重置密码" key="form2" v-if="isUpdate">
        <UserPassword ref="form2"></UserPassword>
      </a-tab-pane>
      <a-tab-pane tab="分配角色" key="form3" v-if="isUpdate">
        <UserRole ref="form3"></UserRole>
      </a-tab-pane>
<!--      <a-tab-pane tab="分配企业" key="form4" v-if="isUpdate">
        <UserCompany ref="form4"></UserCompany>
      </a-tab-pane>
      <a-tab-pane tab="分配部门" key="form5" v-if="isUpdate">
        <UserDept ref="form5"></UserDept>
      </a-tab-pane>-->
    </a-tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, useAttrs, getCurrentInstance, nextTick } from 'vue';
import { BasicDrawer, useDrawerInner } from '@/components/drawer';
import UserForm from '@/views/sys/user/components/UserForm.vue';
import UserPassword from '@/views/sys/user/components/UserPassword.vue';
import UserRole from '@/views/sys/user/components/UserRole.vue';
import UserCompany from '@/views/sys/user/components/UserCompany.vue';
import UserDept from '@/views/sys/user/components/UserDept.vue';
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs();
//是否是更新模式
const isUpdate = ref(true);
//是否显示底部按钮
const showFooter = ref(true);
//当前选中tab
const activeKey = ref('form1');
//当前列表编辑数据对象
const record = ref();
const ctx: any = getCurrentInstance();
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  activeKey.value = 'form1';
  isUpdate.value = !!data?.isUpdate;
  //是否显示底部按钮
  showFooter.value = data?.showFooter ?? true;
  //设置是否显示底部
  setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
  record.value = data;
  handleTabChange();
});

/**
 * 获取标题
 */
function getTitle() {
  return !isUpdate.value ? '新增用户' : '编辑用户';
}

/**
 * tab切换事件
 */
function handleTabChange() {
  nextTick(() => {
    ctx.refs[activeKey.value].setData(record.value);
  });
}

/**
 * 确定按钮事件
 */
async function handleOk() {
  try {
    setDrawerProps({ confirmLoading: true });
    ctx.refs[activeKey.value].handleSubmit(emit, (callback) => {
      //执行子组件回调事件
      callback && callback(emit);
    });
  } finally {
    closeDrawer();
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
